package cn.leaf.config;

import cn.leaf.constants.Constant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * description: 消息队列配置
 *
 * 绑定一个死信队列
 * 当定义的队列消息没有被正常消费就会被放入死信队列做后续处理
 *
 * @author Cyril
 * @version v1.0.0
 * @since 2021-05-20 21:21:31
 *
 */
@Configuration
public class RabbitProducerConfig {

    /**
     * 定义消息死信交换机
     * @return {@link DirectExchange}
     */
    @Bean
    public DirectExchange msgDeadDirectExchange() {
        return new DirectExchange(Constant.MESSAGE_DEAD_DIRECT_EXCHANGE, true, false);
    }

    /**
     * 定义消息死信队列
     * @return {@link Queue}
     */
    @Bean
    public Queue msgDeadDirectQueue() {
        return new Queue(Constant.MESSAGE_DEAD_DIRECT_QUEUE, true);
    }

    /**
     * 绑定死信队列交换机和队列
     * @return {@link Binding}
     */
    @Bean
    public Binding msgDeadBinding() {
        return BindingBuilder.bind(msgDeadDirectQueue()).to(msgDeadDirectExchange()).with(Constant.MESSAGE_DEAD_DIRECT_ROUTING_KEY);
    }

    /**
     * 定义消息交换机
     * @return {@link DirectExchange}
     */
    @Bean
    public DirectExchange msgDirectExchange() {
        return new DirectExchange(Constant.MESSAGE_DIRECT_EXCHANGE, true, false);
    }

    /**
     * 定义消息队列并绑定死信队列
     * @return {@link Queue}
     */
    @Bean
    public Queue msgDirectQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", Constant.MESSAGE_DEAD_DIRECT_EXCHANGE);
        args.put("x-dead-letter-routing-key", Constant.MESSAGE_DEAD_DIRECT_ROUTING_KEY);
        return new Queue(Constant.MESSAGE_DIRECT_QUEUE, true, false, false, args);
    }

    /**
     * 绑定交换机和队列
     * @return {@link Binding}
     */
    @Bean
    public Binding msgBinding() {
        return BindingBuilder.bind(msgDirectQueue()).to(msgDirectExchange()).with(Constant.MESSAGE_DIRECT_ROUTING_KEY);
    }
}
